package cn.moremind.leetcode;

import cn.hutool.core.date.StopWatch;

import java.io.*;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.util.Random;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @author <a href="mailto:hefe@bsoft.com.cn">hefengen</a>
 * @(#) Created on
 * 版权：版权所有 bsoft 保留所有权力。
 * @description
 */
public class CopyFile {


    public static void main(String[] args) throws IOException {
        generateFile(1_000, 4*1024*1024);
        long startTime = System.currentTimeMillis();
        splitFile("D://tmp//test.txt", 10);
//        splitFile2("D://tmp//test.txt", 10);
        System.out.format("split file time: %d", (System.currentTimeMillis() - startTime) / 1000);
    }

    private static final String fileDir = "D://tmp";

    public static void generateFile(int num, int buffSize) throws IOException {
        Random random = new Random();
        String fileTxt = "test2.txt";
        String fileName = fileDir + File.separator + fileTxt;
        FileOutputStream fos = new FileOutputStream(fileName);
        FileChannel fileChannel = fos.getChannel();
        ByteBuffer buffer = ByteBuffer.allocate(buffSize);
        for (int i = 0; i < num ; i++) {
            buffer.clear();
            for (int j = 0; j < buffer.limit(); j++) {
                buffer.put((byte) (97 + random.nextInt(23)));
            }
            buffer.flip();
            fileChannel.write(buffer);
        }
        fileChannel.close();
        fos.close();
    }

    //https://www.cnblogs.com/daoqidelv/p/6884223.html
    public static void splitFile(String file, int fileCount) throws IOException {
        String filePath = new File(file).getParentFile().getPath();
        FileInputStream fileInputStream = new FileInputStream(file);
        FileChannel fileChannel = fileInputStream.getChannel();
        long fileSize = fileChannel.size();
        String tmpFileName = filePath + File.separator + "tmp";
        long simpleFileSize = fileSize / fileCount;
        FileOutputStream fileOutputStream = null;
        FileChannel outChannel = null;
        for (int i = 0; i < fileCount; i++) {
            fileOutputStream = new FileOutputStream(tmpFileName + i + ".txt");
            outChannel = fileOutputStream.getChannel();
            fileChannel.transferTo(simpleFileSize * i, simpleFileSize, outChannel);
            outChannel.close();
            fileOutputStream.close();
        }
        // 关闭读文件流
        fileChannel.close();
        fileInputStream.close();;
    }
    public static void splitFile2(String filePath, int fileCount) throws IOException {
        FileInputStream fis = new FileInputStream(filePath);
        FileChannel inputChannel = fis.getChannel();
        final long fileSize = inputChannel.size();
        long average = fileSize / fileCount;//平均值
        long bufferSize = 2000; //缓存块大小，自行调整
        ByteBuffer byteBuffer = ByteBuffer.allocate(Integer.valueOf(bufferSize + "")); // 申请一个缓存区
        long startPosition = 0; //子文件开始位置
        long endPosition = average < bufferSize ? 0 : average - bufferSize;//子文件结束位置
        for (int i = 0; i < fileCount; i++) {
            if (i + 1 != fileCount) {
                int read = inputChannel.read(byteBuffer, endPosition);// 读取数据
                readW:
                while (read != -1) {
                    byteBuffer.flip();//切换读模式
                    byte[] array = byteBuffer.array();
                    for (int j = 0; j < array.length; j++) {
                        byte b = array[j];
                        if (b == 10 || b == 13) { //判断\n\r
                            endPosition += j;
                            break readW;
                        }
                    }
                    endPosition += bufferSize;
                    byteBuffer.clear(); //重置缓存块指针
                    read = inputChannel.read(byteBuffer, endPosition);
                }
            }else{
                endPosition = fileSize; //最后一个文件直接指向文件末尾
            }

            FileOutputStream fos = new FileOutputStream(filePath + (i + 1));
            FileChannel outputChannel = fos.getChannel();
            inputChannel.transferTo(startPosition, endPosition - startPosition, outputChannel);//通道传输文件数据
            outputChannel.close();
            fos.close();
            startPosition = endPosition + 1;
            endPosition += average;
        }
        inputChannel.close();
        fis.close();

    }

    class Task implements Runnable {

        @Override
        public void run() {

        }
    }

    private ThreadPoolExecutor executor = new ThreadPoolExecutor(10, 10, 60, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>());
    public void splitFilesMultiThread(String file, int fileCount) {
        executor.execute(new Task());
    }
}
